﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Dao;
using System.IO;
using System.Web.UI.HtmlControls;
using System.Text;

namespace Web.Page
{
    public partial class PD_Query : BasePage
    {
        public const string OP_KEY = "op";
        protected const string CONFIRMED = "1";
        protected const string CMD_CONFIRM = "Confirm";

        protected string id;

        JCCD_Dao dao = new JCCD_Dao();
        JCCDMXB_Dao daoMXB = new JCCDMXB_Dao();
        List<vJCCD> jccdList;

        protected void Page_Load(object sender, EventArgs e)
        {
            base.Page_Load(sender, e);
            id = Request.QueryString["id"];

            if (!IsPostBack)
            {
                string op = Request.QueryString["op"];
                this.hdOp.Value = op;
                Cache.Insert(OP_KEY, op);
                string title = "{0}仓单盘点";
                this.lbTitle.Text = string.Format(title, op.CompareTo("1000") < 0 ? "进" : "出");
                this.tbRQStart.Attributes.Add("onclick", "show()");
                this.tbRQEnd.Attributes.Add("onclick", "show()");
                initValue();
                BindGridview();
            }
        }

        private void initValue()
        {
            // 部门
            Departments_Dao daoDep = new Departments_Dao();
            List<Department> lsDep = daoDep.QueryAll();
            this.ddlBM.DataSource = lsDep;
            this.ddlBM.DataTextField = "Name";
            this.ddlBM.DataValueField = "ID";
            this.ddlBM.DataBind();
            this.ddlBM.Items.Insert(0, new ListItem("请选择", "0"));
        }

        protected void GridView1_PageIndexChanged(object sender, EventArgs e)
        {
            BindGridview();
        }

        protected void GridView1_PageIndexChanging(object sender, GridViewPageEventArgs e)
        {
            GridView1.PageIndex = e.NewPageIndex;
            BindGridview();
            SavePageIndex(e.NewPageIndex);
        }

        private void BindGridview()
        {
            GridView1.PageIndex = RestorePageIndex();
            this.GridView1.DataSource = Query();
            this.GridView1.DataBind();
        }

        private List<vJCCD> Query()
        {
            string bh = this.tbBH.Text.Trim();
            string bm = this.ddlBM.SelectedValue.ToString();
            string ry = this.ddlRY.SelectedValue.ToString();
            string cgy = this.ddlCGY.SelectedValue.ToString();

            string lx = hdOp.Value;

            string datetimeStart = this.tbRQStart.Text.Trim();
            string datetimeEnd = this.tbRQEnd.Text.Trim();
            if (!datetimeStart.Equals(string.Empty) && !datetimeEnd.Equals(string.Empty))
            {
                int t = DateTime.Parse(datetimeStart).CompareTo(DateTime.Parse(datetimeEnd));
                if (t > 0)
                {
                    lbResult.Text = "结束时间不能小于开始时间";
                    return null;
                }
            }

            List<vJCCD> list = dao.QueryBySqlEx(lx, bm, ry, cgy, datetimeStart, datetimeEnd);

            return list;
        }

        protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
        {
            if (e.Row.RowType == DataControlRowType.DataRow)
            {
                vJCCD item = (vJCCD)e.Row.DataItem;
                Label lblRQ = ((Label)(e.Row.Cells[5].FindControl("lblRQ")));
                lblRQ.Text = item.RQ.ToString("yyyy-MM-dd HH:ss:dd");
                LinkButton btnConfirm = ((LinkButton)(e.Row.Cells[5].FindControl("btnConfirm")));

                //Button btnViewMXB = ((Button)(e.Row.Cells[9].FindControl("btnViewMXB")));
                //btnViewMXB.CommandArgument = String.Format("{0};{1}", item.ID.ToString(), item.ZT);
                //btnConfirm.CommandArgument = item.ID.ToString();

                //Label lblZT = ((Label)(e.Row.Cells[8].FindControl("lblZT")));
                //if (item.ZT == 0)
                //{
                //    lblZT.Text = "待确认";
                //    lblZT.ForeColor = System.Drawing.Color.Red;
                //    btnConfirm.Visible = true;
                //}
                //else
                //{
                //    lblZT.ForeColor = System.Drawing.Color.Green;
                //    lblZT.Text = "已确认";
                //    btnConfirm.Visible = false;
                //    btnConfirm.OnClientClick = null;
                //}
            }
        }

        protected void GridView1_RowDeleting(object sender, GridViewDeleteEventArgs e)
        {
            string id = GridView1.DataKeys[e.RowIndex].Value.ToString();
            int result = dao.Delete(id);
            if (result == 1)
            {
                lbResult.Text = "删除成功";
                BindGridview();
            }
        }


        protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
        {
            //string id = (string)e.CommandArgument;

            //if (e.CommandName.Equals(CMD_CONFIRM))
            //{
            //    Confirm(id);
            //}
        }

        //protected void Confirm(string id)
        //{
        //    string jccdid = id;
        //    JCCD_Dao dao = new JCCD_Dao();
        //    JCCD jccd = dao.Query(jccdid);
        //    bool res = false;
        //    if (jccd.LX.CompareTo("1000") < 0)
        //    {
        //        res = dao.ConfirmIn(jccdid);
        //    }
        //    else
        //    {
        //        List<Guid> less = new List<Guid>();
        //        res = dao.ConfirmOut(jccdid, ref less);
        //    }

        //    if (res)
        //    {
        //        lbResult.Text = "确认单据成功。";
        //        BindGridview();
        //    }
        //}

        private string getLX(string key)
        {
            string str = "";
            switch (key.Trim())
            {
                case "0001":
                    str = "物料采购进仓";
                    break;
                case "1001":
                    str = "物料采购出仓";
                    break;
            }
            return str;
        }

        protected void ddlBM_SelectedIndexChanged(object sender, EventArgs e)
        {
            this.ddlRY.Items.Clear();
            string depId = ddlBM.SelectedValue;
            if (depId != "0")
            {
                Guid guid = Guid.Parse(depId);
                using (var context = new Dao.ErpEntities())
                {
                    var query = from d in context.UserInDepartmentSet
                                join u in context.UserSet
                                on d.UserId equals u.Id
                                where d.DepartmentId == guid
                                select new
                                {
                                    Id = d.UserId,
                                    Name = u.Name
                                };
                    List<UserNames> list = new List<UserNames>();
                    if (query.Count() > 0)
                    {
                        foreach (var q in query)
                        {
                            UserNames un = new UserNames();
                            un.Id = q.Id.ToString();
                            un.Name = q.Name;
                            list.Add(un);
                        }
                    }

                    this.ddlRY.DataSource = list;
                    this.ddlRY.DataTextField = "Name";
                    this.ddlRY.DataValueField = "Id";
                    this.ddlRY.DataBind();

                    this.ddlCGY.DataSource = list;
                    this.ddlCGY.DataTextField = "Name";
                    this.ddlCGY.DataValueField = "Id";
                    this.ddlCGY.DataBind();
                }
            }

            this.ddlRY.Items.Insert(0, new ListItem("请选择", "0"));
            this.ddlCGY.Items.Insert(0, new ListItem("请选择", "0"));
        }


        protected class UserNames
        {
            public string Id { get; set; }
            public string Name { get; set; }
        }



        protected void btnQuery_Click(object sender, ImageClickEventArgs e)
        {
            this.lbResult.Text = "";
            BindGridview();
        }


        private string GetWPLX(string key)
        {
            string name = "";
            switch (key.Trim())
            {
                case "01":
                    name = "物料";
                    break;
                case "02":
                    name = "产品";
                    break;
                case "03":
                    name = "部件";
                    break;
            }

            return name;
        }

        private string GetDJLX(string key)
        {
            string name = "";
            switch (key.Trim())
            {
                case "0001":
                    name = "物料采购进仓";
                    break;
                case "0002":
                    name = "物料调拨进仓";
                    break;
            }
            return name;
        }

        public override void VerifyRenderingInServerForm(Control control)
        {
        }

        protected void btnExport_Click(object sender, EventArgs e)
        {

            GridView1.AllowPaging = false;
            GridView1.AllowSorting = false;
            GridView1.DataSource = Query();
            GridView1.DataBind();

            try
            {
                Export();
            }
            catch (Exception ex)
            {
                throw new Exception(ex.Message);
            }

            GridView1.AllowPaging = true;
            GridView1.AllowSorting = true;
            GridView1.DataBind();

        }

        private void Export()
        {
            Response.Clear();
            Response.Buffer = true;
            Response.Charset = "UTF-8";
            Response.ContentType = "application/vnd.ms-excel";
            Response.ContentEncoding = Encoding.UTF8;
            Response.AddHeader("content-disposition", "attachment;filename=GridViewExport.xls");

            StringWriter sw = new StringWriter();
            HtmlTextWriter hw = new HtmlTextWriter(sw);
            GridView1.RenderControl(hw);

            string style = @"<style> .textmode { } </style>";
            Response.Write(style);
            Response.Write(sw.ToString());
            Response.Flush();
            HttpContext.Current.ApplicationInstance.CompleteRequest();
            // Response.End();
        }

    }
}